//
//  GameScene.m
//  Hello Cocos
//
//  Created by Tedo on 6/17/10.
//  Copyright 2010 sushigames. All rights reserved.
//

#import "PlayerMenuScene.h"
#import "GameScene.h"
#import "PlayerUnit.h"
#import "EnemyUnit.h"
#import "FightEffect.h"
#import "GameLayer.h"
#import "LevelMgrLayer.h"

@implementation PathsLayer

-(void)draw{
	glColor4f(0.3, 0.3, 0.3, 1.0);  
	glLineWidth(3.0f);
	
	NSArray * allUnits = [PlayerUnit allUnitsNotDead];
	NSUInteger i, count = [allUnits count];
	for (i = 0; i < count; i++) {
		PlayerUnit * unit = (PlayerUnit *)[allUnits objectAtIndex:i];
		if (unit.desiredPosition.x != -1 && unit.desiredPosition.y != -1)
		{
			CGPoint distance = ccpSub([unit desiredPosition], [unit position]);
			if (ccpLength(distance) > 10.0) {
				ccDrawLine(unit.position, unit.desiredPosition);
			}
		}
	}
}    

@end


@implementation EffectsLayer

@synthesize fightEffectSheet;

-(id) init {
	if( (self=[super init] )) {
		// init fight effect array
		fightEffects = [[NSMutableArray alloc] init];
		
		// get sprite sheet
		fightEffectSheet = [CCSpriteSheet spriteSheetWithFile:@"fight_effect.png"];
		[self addChild:fightEffectSheet];
		
		// schedule task to check for battles
//		[self schedule:@selector(checkBattles:)];
	}
	
	return self;
}

-(void)checkBattles:(ccTime)dt {
	for ( FightEffect *effect in fightEffects ) {
		if ( !CGRectIntersectsRect([effect.playerUnit boundingBox], [effect.enemyUnit boundingBox]) ) {
			[effect stopAllActions];
			[fightEffects removeObject:effect];
			[self removeChild:effect cleanup:TRUE];
		}
		else {
			effect.position = ccpMidpoint(effect.playerUnit.position, effect.enemyUnit.position);
		}
	}
	
	for (PlayerUnit *playerUnit in [PlayerUnit allUnits]) {
		for (EnemyUnit *enemyUnit in [EnemyUnit allUnits]) {
			if (CGRectIntersectsRect([playerUnit boundingBox], [enemyUnit boundingBox])) {
				BOOL bFound = FALSE;
				for (FightEffect *effect in fightEffects) {
					if (effect.playerUnit == playerUnit && effect.enemyUnit == enemyUnit) {
						bFound = TRUE;
						break;
					}
				}
				if (!bFound ) {
					FightEffect *effect = [self createEffect:ccpMidpoint(playerUnit.position, enemyUnit.position)];
					effect.playerUnit = playerUnit;
					effect.enemyUnit = enemyUnit;
				}
			}
		}
	}
}

-(FightEffect *)createEffect:(CGPoint)effectPosition {
	FightEffect *fightEffectSprite = [FightEffect spriteWithTexture:fightEffectSheet.texture rect:CGRectMake(0, 0, 128, 128)];
	[self addChild:fightEffectSprite];
	[fightEffects addObject:fightEffectSprite];
	fightEffectSprite.position = effectPosition;
	
	// create CCAnimation from sheet
	// Notes: CCAnimation can't be created once on init and be re-used.. maybe it can, need to figure out.
	CCAnimation *fightEffectAnimation = [CCAnimation animationWithName:@"fightEffect" delay:0.2f];
	for (int x = 0; x < 5; x++) {
		CCSpriteFrame *frame = [CCSpriteFrame frameWithTexture:fightEffectSheet.texture rect:CGRectMake(x*128,0,128,128) offset:ccp(0,0)];
		[fightEffectAnimation addFrame:frame];
		if (x == 0) [fightEffectAnimation addFrame:frame];
	}
	
	CCAnimate *action = [CCAnimate actionWithAnimation:fightEffectAnimation];
	CCRepeatForever *repeat = [CCRepeatForever actionWithAction:action];
	[fightEffectSprite runAction:repeat];
	
	return fightEffectSprite;
}

@end


@implementation UILayer

@synthesize icon1, icon2, icon3;

NSMutableArray *quitTouches = nil;

- (id)init {
    self = [super init];
    if (self) {
		if (quitTouches == nil)
            quitTouches = [[NSMutableArray alloc] init];
		
		CCColorLayer *transBg = [CCColorLayer node];
		[transBg initWithColor:ccc4(0, 0, 0, 150)];
		[self addChild:transBg];
		
		icon1 = [CCSprite spriteWithFile:@"iconWhite.png"];
		[self addChild:icon1];
		
		icon2 = [CCSprite spriteWithFile:@"iconBlue.png"];
		[self addChild:icon2];
		
		icon3 = [CCSprite spriteWithFile:@"iconRed.png"];
		[self addChild:icon3];
	}
	return self;
}

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	
	[quitTouches addObject:touch];
}
- (void)ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch; 
	for ( touch in touches ) {
	}
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch; 
	for ( touch in touches ) {
		if ( [quitTouches containsObject:touch] && touch.tapCount >= 2 ) {
			[self disableLayer];
		}
	}
}
- (void)ccTouchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
	NSLog( @"Touch Cancelled" );
}

- (void)enableLayer {
	self.visible = TRUE;
	self.isTouchEnabled = YES;
}

- (void)disableLayer {
	self.visible = FALSE;
	self.isTouchEnabled = NO;
	
	GameScene * scene = (GameScene *)[self parent];
	[scene gameLayer].isTouchEnabled = YES;
	
	[quitTouches removeObjectsInRange:NSMakeRange(0, quitTouches.count)];
}

- (void)createAbilityButtons:(CGPoint)originLocation {
	icon1.position = originLocation;
	[icon1 runAction: [CCMoveTo actionWithDuration:0.3 position: ccpAdd(originLocation, ccp(80, 80)) ]];
	
	icon2.position = originLocation;
	[icon2 runAction: [CCMoveTo actionWithDuration:0.3 position: ccpAdd(originLocation, ccp(100, 0)) ]];
	
	icon3.position = originLocation;
	[icon3 runAction: [CCMoveTo actionWithDuration:0.3 position: ccpAdd(originLocation, ccp(80, -80)) ]];
}

@end


@implementation GameScene

@synthesize gameLayer, pathsLayer, effectsLayer, uiLayer, levelMgrLayer;

+(id) sceneWithLevel:(NSString *)levelName
{
	GameScene *scene = [GameScene node];
	
	PathsLayer *pathsLayer = [PathsLayer node];
	scene.pathsLayer = pathsLayer;
	
	GameLayer *gameLayer = [GameLayer node];
    scene.gameLayer = gameLayer;
	
	EffectsLayer *effectsLayer = [EffectsLayer node];
	scene.effectsLayer = effectsLayer;
	
	CCColorLayer *bgLayer = [CCColorLayer node];
	[bgLayer initWithColor:ccc4(180, 180, 180, 255)];
	
	UILayer *uiLayer = [UILayer node];
	scene.uiLayer = uiLayer;
	uiLayer.visible = FALSE;
	
	LevelMgrLayer *levelMgrLayer = [LevelMgrLayer nodeWithLevel:levelName];
	scene.levelMgrLayer = levelMgrLayer;
	
	// add layers in desired order
	[scene addChild:bgLayer];
	[scene addChild:pathsLayer];
	[scene addChild:gameLayer];
	[scene addChild:effectsLayer];
	[scene addChild:uiLayer];	// Fad: replace this layer with your prototype
	[scene addChild:levelMgrLayer];
	
	return scene;
}

- (void) dealloc {
	//*NOTE* Not sure about order here
	
	[pathsLayer release];
	[gameLayer release];
	[uiLayer release];
	[effectsLayer release];
	
	[super dealloc];
	
	[PlayerUnit clearAllUnits];
	[EnemyUnit clearAllUnits];
	[Unit clearAllUnits];
}

@end
